package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void insert(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insertAddress(addressBook);
    }

    /**
     * 查询所有地址
     * @return
     */
    @Override
    public List<AddressBook> getAddress() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook=new AddressBook();
        addressBook.setUserId(userId);
        List<AddressBook>addressBookList=addressBookMapper.getAddress(addressBook);
        return addressBookList;
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public List<AddressBook> getDefaultAddress() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook=new AddressBook();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(1);
        List<AddressBook>addressBookList=addressBookMapper.getAddress(addressBook);
        return addressBookList;
    }

    /**
     * 根据id修改地址信息
     * @param addressBook
     */
    @Override
    public void updateAddress(AddressBook addressBook) {
        addressBookMapper.updateById(addressBook);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook selectById(Long id) {
        AddressBook addressBook=addressBookMapper.selectById(id);
        return addressBook;
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteAddressById(id);
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    @Override
    public void setDefaultAddress(AddressBook addressBook) {
        //先把当前用户所有地址的默认值置0,
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        log.info("所有地址默认值置0");
        addressBookMapper.updateDefault(addressBook);
        //再把当前地址的默认值置为1
        addressBook.setIsDefault(1);
        log.info("当前地址默认值设为1");
        addressBookMapper.updateById(addressBook);
    }
}
